package com.situ.vivamarket.api.sys;

import com.situ.vivamarket.util.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "/sys/api/v1/ue",produces = MediaType.APPLICATION_JSON_VALUE)
public class UEditorApi {
    @Value("${custom.file.upload.location}") //spring表达式，取得属性值
    private String uploadLocation;

    @RequestMapping
    public ResponseEntity<Object> action(String action, MultipartFile file, HttpServletRequest req) throws IOException {
        if (action.equals("config")) { //获取配置
            try(InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("ue_config.json")){

                String config=StreamUtils.copyToString(is, StandardCharsets.UTF_8);
                return ResponseEntity.ok(config);

            }catch (Exception e){
                e.printStackTrace();
            }
        }else if (action.equals("image")) { //上传图片,图片名字和文件名跟配置里的一致
                String type="ueditor";

            File fileDir = new File(uploadLocation + File.separator + type);//用于创建目录
            if(!fileDir.exists()){
                boolean success=fileDir.mkdirs();
                if(!success){
                    return ResponseEntity.internalServerError().body(JsonResult.fail("创建目录失败"));
                }
            }
//        生成文件名
            String fileName = file.getOriginalFilename();//上传时候的文件名
            String ext = fileName.substring(fileName.lastIndexOf("."));//扩展名，后缀
            fileName = UUID.randomUUID().toString() + ext;//全局，唯一的随机数
//      目标文件
            File desc = new File(fileDir.getCanonicalPath() + File.separator + fileName);
//    复制文件
            file.transferTo(desc);
//    响应数据
            Map data=Map.of(
                    "state","SUCCESS",
                    "url", req.getContextPath()+"/assets/"+type+"/"+fileName);
            return ResponseEntity.ok(data);
        }
            return ResponseEntity.notFound().build();
    }
}
